import 'package:card_swiper/card_swiper.dart';
import 'package:easy_read_comic/internal/api/swiper_api.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../models/swiper_model.dart';

class SwiperWidgetController extends GetxController {
  List<SwiperModel> list = [];

  @override
  void onInit() {
    super.onInit();
    this.getSwiperList();
  }

  void getSwiperList() async {
    SwiperApi().swiper().then((value) {
      if (value.data["data"] != null) {
        for (var item in value.data["data"]) {
          this.list.add(SwiperModel.fromJson(item));
        }
        update();
      }
    });
  }
}

class SwiperWidget extends StatelessWidget {
  SwiperWidget(this.width, this.height, {this.allPadding = 0});

  double allPadding = 0;

  double width = Get.width;

  double height = 200;

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      builder: (controller) {
        return Container(
          padding: EdgeInsets.all(allPadding),
          child: Swiper(
            autoplay: false,
            loop: false,
            pagination: SwiperPagination(
              alignment: Alignment.bottomCenter,
              margin: EdgeInsets.only(
                bottom: 0,
              ),
            ),
            itemCount: controller.list.length,
            itemBuilder: (context, index) {
              return ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: ExtendedImage.network(
                  controller.list[index].Thumb,
                  fit: BoxFit.cover,
                  enableLoadState: true,
                  loadStateChanged: (ExtendedImageState state) {
                    switch (state.extendedImageLoadState) {
                      case LoadState.loading:
                        return Center(
                          child: LoadingAnimationWidget.discreteCircle(
                            color: Colors.white,
                            size: 50,
                          ),
                        );
                      case LoadState.completed:
                        return state.completedWidget;
                      case LoadState.failed:
                        return Center(
                          child: Icon(
                            Icons.error,
                            color: Colors.red,
                          ),
                        );
                    }
                    return null;
                  },
                ),
              );
            },
          ),
          width: this.width,
          height: this.height,
        );
      },
      init: SwiperWidgetController(),
    );
  }
}
